package auto;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;



public class AutoMain {

	static final String DEFAULT_INSTALL_NAME="auto.jar";
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	   String jar = AutoMain.class.getProtectionDomain().
	   getCodeSource().getLocation().toString().substring(6);
	   List<File> depressFs=new LinkedList<File>();
	   ZipFile zip=null;
		InputStream in=null;
		OutputStream out=null;
	   try {
		JarFile jarF=new JarFile(jar);
		Enumeration<JarEntry> em=jarF.entries();
		
		while(em.hasMoreElements()){
			JarEntry en=em.nextElement();
			String enName=en.getName().toLowerCase();
			if(enName.startsWith("mysql")||
					enName.startsWith("php")||
					enName.startsWith("nginx")){
				depressFs.add(new File(".",enName));
						//new File(".",enName));
			}
			
					
		}
		
		System.out.print("Decompress Jar File.\nLoad");
		
		
		for(File file:depressFs){
			
			
			File zipFile=new File(file.getAbsolutePath());
			in=new BufferedInputStream(jarF.getInputStream(jarF.getEntry(file.getName())));
			out=new BufferedOutputStream(new FileOutputStream(zipFile),2048);
			byte [] buffer=new byte[2048];
			for(;;){
				int nByte=in.read(buffer);
				if(nByte<=0)break;
				out.write(buffer,0,nByte);
			}
			out.flush();
			out.close();
			in.close();
		
			System.out.println(zipFile.getAbsolutePath());
			zip=new ZipFile(zipFile.getAbsolutePath());
			Enumeration<?> e = zip.entries();
			while(e.hasMoreElements()){
				ZipEntry en=(ZipEntry) e.nextElement();
			
				if(en.isDirectory()){
					new File(en.getName()).mkdir();
					continue;
				}
			
				System.out.println(en.getName());
				in=new BufferedInputStream(zip.getInputStream(en));
				out=new BufferedOutputStream(new FileOutputStream(en.getName()));
				buffer=new byte[2048];
				for(;;){
					int nByte=in.read(buffer);
					if(nByte<=0)break;
					out.write(buffer,0,nByte);
				}
				out.flush();
				out.close();
				in.close();
				
			}
			zip.close();
			
		}
		System.out.println("Completed");
		
		
	} catch (IOException e) {
		e.printStackTrace();
		try {
		out.close();
		in.close();
		zip.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	} finally{
		for(File file:depressFs){
			System.out.println("del"+file.getAbsoluteFile());
			file.delete();
		}
	}
	   
	 

	
	}

}
